//
//  ExceptionView.m
//  bestkeep
//
//  Created by 武探 on 2016/12/15.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "ExceptionView.h"

typedef void(^ExceptionViewActionHandler)(ExceptionViewAction *action);

@interface ExceptionViewAction()

@property(nonatomic,copy) ExceptionViewActionHandler handler;

@end

@implementation ExceptionViewAction

- (instancetype)initWithTitle:(NSString*)title handler:(void (^)(ExceptionViewAction *))handler {
    self = [super init];
    if(self) {
        _title = title;
        self.handler = handler;
    }
    return self;
}

- (instancetype)initWithType:(ExceptionCodeType)type handler:(void (^)(ExceptionViewAction *))handler
{
    self = [super init];
    if(self) {
        _type = type;
        self.handler = handler;
    }
    return self;
}

+ (instancetype)actionWithTitle:(NSString *)title handler:(void (^)(ExceptionViewAction *))handler {
    ExceptionViewAction *action = [[ExceptionViewAction alloc] initWithTitle:title handler:handler];
    
    return action;
}

+ (instancetype)actionWithType:(ExceptionCodeType)type handler:(void(^)(ExceptionViewAction *action))handler{
    ExceptionViewAction *action = [[ExceptionViewAction alloc] initWithType:type handler:handler];
    
    return action;
}
@end




@interface ExceptionView()

@property(nonatomic,strong) UIImageView *imageView;
@property(nonatomic,strong) NSMutableArray<ExceptionViewAction*> *actions;
@property(nonatomic,strong) NSMutableArray<UIButton*> *buttons;

@end

@implementation ExceptionView

-(instancetype)initWithTitle:(NSString *)title
{
    self = [super init];
    if(self) {
        _title = title;
        [self _initialize];
    }
    return self;
}

-(instancetype)initWithType:(ExceptionCodeType)type
{
    self = [super init];
    if (self) {
        _type = type;
        [self _initialize];
    }
    return self;
}



+(instancetype)exceptionViewWithTitle:(NSString *)title
{
    ExceptionView *view = [[ExceptionView alloc] initWithTitle:title];
    return view;
}

+ (instancetype)exceptionViewWithType:(ExceptionCodeType)type
{
    ExceptionView *view = [[ExceptionView alloc] initWithType:type];
    return view;
}

- (UILabel *)titleLabel {
    
    if (!_titleLabel) {
        
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textColor = [UIColor colorWithRed:0.25 green:0.25 blue:0.25 alpha:1.00];
        _titleLabel.font = [UIFont systemFontOfSize:20];
        _titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        _titleLabel.numberOfLines = 0;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UILabel *)contentLabel {
    
    if (!_contentLabel) {
        _contentLabel = [[UILabel alloc] init];
        _contentLabel.textColor = [UIColor colorWithRed:0.25 green:0.25 blue:0.25 alpha:1];
        _contentLabel.font = [UIFont systemFontOfSize:14];
        _contentLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        _contentLabel.numberOfLines = 0;
        _contentLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_contentLabel];
    }
    return _contentLabel;
}

-(void)_initialize {
    
    self.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1];
    
    _actions = [NSMutableArray array];
    _buttons = [NSMutableArray array];
    
    _imageView = [[UIImageView alloc] init];
    _imageView.image = [self imageWithType:_type];
    [self addSubview:_imageView];
    
    self.titleLabel.text = [self titleWithType:_type];
    self.contentLabel.text = [self contentWithType:_type];

    [self makeConstraints];
}


- (void)makeConstraints
{
    UIView *baseView = _type == ExceptionCodeTypeSearchIsEmpty ? _imageView : self.titleLabel;
    CGFloat contentLabelTopConstant = _type == ExceptionCodeTypeSearchIsEmpty ? 30 : 10;
    
    // image view
    _imageView.translatesAutoresizingMaskIntoConstraints = NO;
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    NSLayoutConstraint *imageViewCenterYConstraint = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationLessThanOrEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1  constant:ScreenHeight<700?(ScreenHeight<600?(ScreenHeight<500?-ScreenHeight/2.f+160:-ScreenHeight/2.f+180):-ScreenHeight/2.f+220):-ScreenHeight/2.f+260 ];
    NSLayoutConstraint *imageViewCenterXConstraint = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationLessThanOrEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    
    
    NSLayoutConstraint *imageViewWidthConstraint = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:0.7 constant:0];
    NSLayoutConstraint *imageViewHeightConstraint = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationLessThanOrEqual toItem:_imageView attribute:NSLayoutAttributeHeight multiplier:1 constant:0];
    
    [self addConstraints:@[imageViewCenterYConstraint, imageViewCenterXConstraint, imageViewWidthConstraint, imageViewHeightConstraint]];
    
   
    
    //title label
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *titleLabelTopConstraint = [NSLayoutConstraint constraintWithItem:self.titleLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_imageView attribute:NSLayoutAttributeBottom multiplier:1 constant:30];
    NSLayoutConstraint *titleLabelCenterXConstraint = [NSLayoutConstraint constraintWithItem:self.titleLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    [self addConstraints:@[titleLabelTopConstraint, titleLabelCenterXConstraint]];
    
    //content label
    self.contentLabel.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *contentLabelTopConstraint = [NSLayoutConstraint constraintWithItem:self.contentLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:baseView attribute:NSLayoutAttributeBottom multiplier:1 constant:contentLabelTopConstant];
    NSLayoutConstraint *contentLabelCenterXConstraint = [NSLayoutConstraint constraintWithItem:self.contentLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    [self addConstraints:@[contentLabelTopConstraint, contentLabelCenterXConstraint]];

}

-(void)addAction:(ExceptionViewAction *)action {
    if(!action) {
        return;
    }
    if([_actions containsObject:action]) {
        return;
    }
    
    [_actions addObject:action];
    
    UIView *baseView = _buttons.lastObject ? _buttons.lastObject : self.contentLabel;
//    CGFloat buttonTopConstantValue = _buttons.lastObject ? 10 : 30;
    
    UIButton *button = [[UIButton alloc] init];
    [button setTitle:[self btnTitleWithType:action.type] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button setBackgroundColor:[UIColor colorWithRed:0.105 green:0.734 blue:0.605 alpha:1]];
    [button addTarget:self action:@selector(buttonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 4;
    button.layer.borderColor = [UIColor colorWithRed:0.105 green:0.734 blue:0.605 alpha:1].CGColor;
    button.layer.borderWidth = 1;
    [self addSubview:button];
    
    [_buttons addObject:button];
    
    button.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *buttonTopConstraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:baseView attribute:NSLayoutAttributeBottom multiplier:1 constant:30];
    
    NSLayoutConstraint *buttonCenterXConstraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    NSLayoutConstraint *buttonWidthConstraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:0 constant:135];
    NSLayoutConstraint *buttonHeightConstraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:0 constant:35];
    [self addConstraints:@[buttonTopConstraint, buttonCenterXConstraint, buttonWidthConstraint, buttonHeightConstraint]];
}

-(void)showInView:(UIView *)view {
    self.frame = view.bounds;
    [view addSubview:self];
}

-(void)buttonTouchUpInside:(UIButton*)sender {
    NSInteger index = [_buttons indexOfObject:sender];
    
    ExceptionViewAction *action = _actions[index];
    if(action.handler) {
        action.handler(action);
    }
}

-(void)dismiss {
    
    UIView *superView = self.superview;
    if(superView) {
        for (UIView *view in superView.subviews) {
            if([view isKindOfClass:[ExceptionView class]]) {
                [view removeFromSuperview];
            }
        }
    }
}

- (NSString *)titleWithType:(ExceptionCodeType)type
{
    NSString *title;
    
    switch (type) {
        case ExceptionCodeTypeNoData:
            title = @"暂无数据~";
            break;
        case ExceptionCodeTypeServerError:
            title = @"服务器出错！";
            break;
        case ExceptionCodeTypeFailedToLoad:
            title = @"加载失败了~";
            break;
        case ExceptionCodeTypeNoNetwork:
            title = @"喔，出错了~";
            break;
        case ExceptionCodeTypeRequestFailed:
            title = @"请求超时~";
            break;
        case ExceptionCodeTypeSearchIsEmpty:
            title = @"";
            break;
        case ExceptionCodeTypeEmptyPages:
            title = @"没有内容";
            break;
        default:
            break;
    }
    
    return title;
}

- (NSString *)contentWithType:(ExceptionCodeType)type
{
    NSString *content;
    switch (type) {
        case ExceptionCodeTypeNoData:
            content = @"请连接到网络，再试一次";
            break;
        case ExceptionCodeTypeServerError:
            content = @"请连接到网络，再试一次";
            break;
        case ExceptionCodeTypeFailedToLoad:
            content = @"请连接到网络，再试一次";
            break;
        case ExceptionCodeTypeNoNetwork:
            content = @"请连接到网络，再试一次";
            break;
        case ExceptionCodeTypeRequestFailed:
            content = @"请连接到网络，再试一次";
            break;
        case ExceptionCodeTypeSearchIsEmpty:
            content = @"对不起，没有找到您想要的商品";
            break;
        case ExceptionCodeTypeEmptyPages:
            content = @"暂无消息";
            break;
        default:
            break;
    }
    
    return content;
}

- (NSString *)btnTitleWithType:(ExceptionCodeType)type
{
    NSString *btnTitle;
    switch (type) {
        case ExceptionCodeTypeNoData:
            btnTitle = @"重新加载";
            break;
        case ExceptionCodeTypeServerError:
            btnTitle = @"重新加载";
            break;
        case ExceptionCodeTypeFailedToLoad:
            btnTitle = @"重新加载";
            break;
        case ExceptionCodeTypeNoNetwork:
            btnTitle = @"重新加载";
            break;
        case ExceptionCodeTypeRequestFailed:
            btnTitle = @"重新加载";
            break;
        case ExceptionCodeTypeSearchIsEmpty:
            btnTitle = @"";
            break;
        case ExceptionCodeTypeEmptyPages:
            btnTitle = @"刷新试试";
            break;
        default:
            break;
    }
    
    return btnTitle;
}

- (UIImage *)imageWithType:(ExceptionCodeType)type
{
    NSString *imageString;
    switch (type) {
        case ExceptionCodeTypeNoData:
            imageString = @"ExceptionCodeTypeNoData";
            break;
        case ExceptionCodeTypeServerError:
            imageString = @"ExceptionCodeTypeServerError";
            break;
        case ExceptionCodeTypeFailedToLoad:
            imageString = @"ExceptionCodeTypeFailedToLoad";
            break;
        case ExceptionCodeTypeNoNetwork:
            imageString = @"ExceptionCodeTypeNoNetwork";
            break;
        case ExceptionCodeTypeRequestFailed:
            imageString = @"ExceptionCodeTypeRequestFailed";
            break;
        case ExceptionCodeTypeSearchIsEmpty:
            imageString = @"ExceptionCodeTypeSearchIsEmpty";
            break;
        case ExceptionCodeTypeEmptyPages:
            imageString = @"ExceptionCodeTypeEmptyPages";
            break;
        default:
            break;
    }
    
    return [UIImage imageNamed:imageString];
}

- (void)dealloc
{
    NSLog(@"exceptionView  dealloc");
}


//TODO:专为首页写的临时解决方案
-(instancetype)initWithType:(ExceptionCodeType)type controller:(UIViewController*)controller
{
    self = [super init];
    if (self) {
        _type = type;
        [self initViewWithContorller:controller];
    }
    return self;
}

+(instancetype)exceptionViewWithType:(ExceptionCodeType)type controller:(UIViewController*)controller{
    ExceptionView *view = [[ExceptionView alloc] initWithType:type controller:controller];
    return view;
}

-(void)initViewWithContorller:(UIViewController*)controller{
    
    self.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1];
    
    _actions = [NSMutableArray array];
    _buttons = [NSMutableArray array];
    
    _imageView = [[UIImageView alloc] init];
    _imageView.image = [self imageWithType:_type];
    [self addSubview:_imageView];
    
    self.titleLabel.text = [self titleWithType:_type];
    self.contentLabel.text = [self contentWithType:_type];
    
    self.titleLabel.font = [UIFont systemFontOfSize:18];
    self.contentLabel.font = [UIFont systemFontOfSize:13];
    
    [self makeConstraint];
}


- (void)makeConstraint{
    UIView *baseView = _type == ExceptionCodeTypeSearchIsEmpty ? _imageView : self.titleLabel;
    CGFloat contentLabelTopConstant = _type == ExceptionCodeTypeSearchIsEmpty ? 30 : 10;
    
    
    CGFloat x = 0;
    if ([UIScreen mainScreen].bounds.size.height == 568) {
        x = -60;
    }else if([UIScreen mainScreen].bounds.size.height < 500){
        x = -40;
    }
    // image view
    _imageView.translatesAutoresizingMaskIntoConstraints = NO;
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    NSLayoutConstraint *imageViewCenterYConstraint = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationLessThanOrEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1  constant:x];
    NSLayoutConstraint *imageViewCenterXConstraint = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationLessThanOrEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    
    
    NSLayoutConstraint *imageViewWidthConstraint = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self attribute:NSLayoutAttributeWidth multiplier: (x==-40) ? 0.4:0.6 constant:0];
    NSLayoutConstraint *imageViewHeightConstraint = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationLessThanOrEqual toItem:_imageView attribute:NSLayoutAttributeHeight multiplier:1 constant:0];
    
    [self addConstraints:@[imageViewCenterYConstraint, imageViewCenterXConstraint, imageViewWidthConstraint, imageViewHeightConstraint]];
    
    
    
    //title label
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *titleLabelTopConstraint = [NSLayoutConstraint constraintWithItem:self.titleLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_imageView attribute:NSLayoutAttributeBottom multiplier:1 constant:(x==-40) ? -20:30];
    NSLayoutConstraint *titleLabelCenterXConstraint = [NSLayoutConstraint constraintWithItem:self.titleLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    [self addConstraints:@[titleLabelTopConstraint, titleLabelCenterXConstraint]];
    
    //content label
    self.contentLabel.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *contentLabelTopConstraint = [NSLayoutConstraint constraintWithItem:self.contentLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:baseView attribute:NSLayoutAttributeBottom multiplier:1 constant:(x==-40) ? 0:contentLabelTopConstant];
    NSLayoutConstraint *contentLabelCenterXConstraint = [NSLayoutConstraint constraintWithItem:self.contentLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    [self addConstraints:@[contentLabelTopConstraint, contentLabelCenterXConstraint]];
}

@end
